<?php

/**
 * 对微信小程序用户加密数据的解密示例代码.
 *
 * @copyright Copyright (c) 1998-2014 Tencent Inc.
 */

namespace app\common\service\wxapi;

use Curl\Curl;
use http\Env\Url;
use think\facade\Cache;
use think\facade\Log;

class WxBizDataCrypt
{
    private $appid;
//	private $sessionKey;
	private $appsecret;
	private $apiAuth;

    public static $OK = 0;
    public static $IllegalAesKey = -41001;
    public static $IllegalIv = -41002;
    public static $IllegalBuffer = -41003;
    public static $DecodeBase64Error = -41004;

	/**
	 * 构造函数
	 * @param $sessionKey string 用户在小程序登录后获取的会话密钥
	 * @param $appsecret string 小程序的appsecret
	 * @param $appid string 小程序的appid
	 * @param $apiAuth string 小程序的用户登录凭证
	 */
	public function __construct( $appid, $appsecret, $apiAuth=null)
	{
//		$this->sessionKey = $sessionKey;
		$this->appsecret = $appsecret;
		$this->appid = $appid;
		$this->apiAuth = $apiAuth;
	}


	/**
	 * 检验数据的真实性，并且获取解密后的明文.
	 * @param $encryptedData string 加密的用户数据
	 * @param $iv string 与用户数据一同返回的初始向量
	 * @param $sessionKey string 用户在小程序登录后获取的会话密钥
	 * @param $data string 解密后的原文
     *
	 * @return int 成功0，失败返回对应的错误码
	 */
	public function decryptData($encryptedData, $iv, $sessionKey, &$data)
	{
		if (strlen($sessionKey) != 24) {
			return self::$IllegalAesKey;
		}
		$aesKey=base64_decode($sessionKey);

        
		if (strlen($iv) != 24) {
			return self::$IllegalIv;
		}
		$aesIV=base64_decode($iv);

		$aesCipher=base64_decode($encryptedData);
		$result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

		$dataObj=json_decode( $result );
		Log::error('result：'. $result);
		Log::error('aesCipher：'. $aesCipher);
		if( $dataObj  == NULL )
		{
			return self::$IllegalBuffer;
		}
		if( $dataObj->watermark->appid != $this->appid )
		{
			return self::$IllegalBuffer;
		}
		$data = $result;
		return self::$OK;
	}

    /**
     * 用户登录凭证（有效期五分钟）。开发者需要在开发者服务器后台调用 auth.code2Session，使用 code 换取 openid、unionid、session_key 等信息
     * @param $code
     * @Author ZHC(codecookies@163.com)
     * @Date 2021-12-08 18:11 星期三
     * @Version 1.0
     * @return mixed
     */
	public function getWechatData($code)
    {
//        if (!$code) {
//            $cache = Cache::get('session_key_wx_'.$this->apiAuth);
//            return json_decode($cache, true);
//        }

        $app_id = $this->appid;
        $app_secret = $this->appsecret;

        $api = "https://api.weixin.qq.com/sns/jscode2session?appid={$app_id}&secret={$app_secret}&js_code={$code}&grant_type=authorization_code";
        $curl = new Curl();
        $curl->setOpt(CURLOPT_SSL_VERIFYPEER, false);
        $curl->get($api);
        $res = $curl->response;
        $data = json_decode($res, true);
        Log::error('Data:'. $res);
//        if ($data && !isset($data['errcode']) && isset($data['openid'])){
//            $sign = $this->apiAuth ? $this->apiAuth : $data['openid'];
//            Cache::set('session_key_doctor_'.$sign, $res, 60*60*24*3);
//        }

        return $data;
    }

}

